package com.campfire.intelligentsecurity.business.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.campfire.intelligentsecurity.business.bean.TOfflineInfo;
import com.campfire.intelligentsecurity.business.bean.TSysRole;
import com.campfire.intelligentsecurity.sys.service.BaseService;
import com.campfire.intelligentsecurity.sys.service.WzMsgPushServer;
import com.github.drinkjava2.jsqlbox.DbContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.github.drinkjava2.jsqlbox.DB.noBlank;
import static com.github.drinkjava2.jsqlbox.DB.par;

@Service
public class OffLineService extends BaseService {

    @Autowired
    @Qualifier("main")
    DbContext dbContext;

    @Autowired
    Environment environment;

    public Object List(){
        StringBuffer sql=new StringBuffer();
        sql.append(" SELECT t1.id,t1.vname,t1.event,t1.url,t1.status,t1.createTime,t1.sf,t1.len,t1.size,(select count(1) from t_event_offline t2 where t2.offline=t1.id) wzCount,(select count(1) from t_person_offline t3 where t3.offline=t1.id) ryCount FROM t_offline_info t1");
        sql.append(" WHERE 1=1 ");
        return builder(sql.toString()," order by t1.createTime desc ");
    }

    public Object offlineList(){
        StringBuffer sql=new StringBuffer();
        sql.append(" SELECT id FROM t_offline_info WHERE status=1");
        return dbContext.qryMapList(sql.toString());
    }

    public Object eventList(){
        StringBuffer sql=new StringBuffer();
        sql.append(" select t.id,ifnull(t1.eventName,'未知违章类型') eventName,'未知作业单位' construction_name,t.state,t.createTime,t.imagePath,t.videoPath from t_event_offline t left join t_sys_event_name t1 on t.algorithmId=t1.algorithmMsg ");
        sql.append(" WHERE 1=1 ");
        return builder(sql.toString()," order by createTime desc ");
    }
    public Object getPersonOffline(String offlineId){
        StringBuffer sql=new StringBuffer();
        sql.append(" select ifnull(name,'陌生人') name,ifnull(faceImage,'') faceImage,createTime from t_person_offline where offline=? ");
        return dbContext.qryMapList(sql.toString(),par(offlineId),"order by createTime desc");
    }

    public Object saveOrUpdate(TOfflineInfo info) {
        if (info.getId() != null) {
            info.update();
        } else {
            info.insert();
        }
        return true;
    }

    public Object offlineJx(String event, String id,String sfId){
        JSONObject camera=new JSONObject();
        Map map=dbContext.qryMap("select id,IFNULL(url,'') AS url,IFNULL(sf,'') AS sf from t_offline_info where id=? ",par(id));
        if (map!=null&&map.size()>0){
            String camera_code="offline_"+map.get("id");
            if(!StrUtil.isEmpty(camera_code)){
                camera = new JSONObject();
                camera.set("CAMERA_CODE", camera_code);
                camera.set("STREAM", map.get("url"));
            }
        }
        String sf=dbContext.qryString("select GROUP_CONCAT(DISTINCT algorithmKey) algorithmKey from t_sys_event_name where algorithmMsg in('" + sfId.replaceAll(",", "','") + "')");
        String body = StrUtil.format("{\"msgType\":201,\"data\":{\"CAMERA_ADD\":{}," +
                "\"CAMERA_REMOVE\":\"{}\",\"ALGORITHM_LIST\":\"{}\"}}", camera, "", sf);
        LOG.info("获取当前监测的视频流信息：{}", body);
        String rs = null;
        JSONObject json=null;
        try {
            rs = HttpUtil.post(environment.getProperty("local.api"), body, 3000);
            LOG.info("返回信息rs：{}", rs);
            if (JSONUtil.parseObj(rs).get("code")!=null){
                if (JSONUtil.parseObj(rs).get("code").equals(200)){
                    json=JSONUtil.parseObj(rs);
                    dbContext.exe("update t_offline_info set status=?,sf=? where id=? ",par(1,sfId,id));
                }
            }
            return json;
        } catch (Exception e) {
            return "行为识别接口服务无法访问";
        }
    }

    public Object startJx(String id,String sfId) {
        dbContext.exe("update t_offline_info set status=?,sf=? where id=? ",par(1,sfId,id));
        return true;
    }

    public Object updStatus(String ids) {
        return dbContext.exe("update t_offline_info set status='2' where id in('" + ids.replaceAll(",", "','") + "')");
    }

    public Object remove(String ids) {
        return dbContext.exe("delete from t_offline_info where id in('" + ids.replaceAll(",", "','") + "')");
    }

    public Object wzqr(String id,String state) {
        return dbContext.exe("update t_event_offline set state=? where id = ? ",par(state,id));
    }
}
